package com.yhy.common.wechat.util;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.yhy.common.wechat.config.WxConfig;
import com.yhy.common.wechat.model.WxResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;

import java.util.Objects;

@Slf4j
public class WxMaUtil {

    /**
     * 小程序获取用户信息
     *
     * @param appId         appid
     * @param jsCode        jsCode
     * @param encryptedData 加密串
     * @param ivStr         偏移量
     * @return WxResult<WxMaUserInfo>
     */
    @SneakyThrows
    public static WxResult<WxMaUserInfo> getUserInfo(String appId, String jsCode, String encryptedData, String ivStr) {
        final WxMaService service = WxConfig.getMaServices().get(appId);
        if (Objects.isNull(service) || !service.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置，请核实！", appId));
        }
        WxMaUserInfo userInfo;
        try {
            WxMaJscode2SessionResult sessionInfo = service.getUserService().getSessionInfo(jsCode);
            userInfo = service.getUserService().getUserInfo(sessionInfo.getSessionKey(), encryptedData, ivStr);
        } catch (WxErrorException e) {
            log.error("解析小程序用户信息失败: {}", e.getLocalizedMessage(), e);
            return WxResult.fail(e);
        } catch (Exception e) {
            log.error("获取小程序用户信息失败: {}", e.getLocalizedMessage());
            throw e;
        }
        return WxResult.ok(userInfo);
    }

    /**
     * 小程序获取用户手机号
     *
     * @param appId         appid
     * @param jsCode        jsCode
     * @param encryptedData 加密串
     * @param ivStr         偏移量
     * @return WxResult<WxMaPhoneNumberInfo>
     */
    @SneakyThrows
    public static WxResult<WxMaPhoneNumberInfo> getPhone(String appId, String jsCode, String encryptedData, String ivStr) {
        final WxMaService service = WxConfig.getMaServices().get(appId);
        if (Objects.isNull(service) || !service.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置，请核实！", appId));
        }
        WxMaPhoneNumberInfo userInfo;
        try {
            WxMaJscode2SessionResult sessionInfo = service.getUserService().getSessionInfo(jsCode);
            userInfo = service.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(), encryptedData, ivStr);
        } catch (WxErrorException e) {
            log.error("解析小程序手机号失败: {}", e.getLocalizedMessage(), e);
            return WxResult.fail(e);
        } catch (Exception e) {
            log.error("获取小程序手机号失败: {}", e.getLocalizedMessage());
            throw e;
        }
        return WxResult.ok(userInfo);
    }

}
